'use strict'

const Koa = require('koa');
const http = require('http');
const path = require('path');
const serve = require('koa-static');
const SocketIo = require('socket.io');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

// 创建koa实例对象
const app = new Koa();

//获取server实例对象
const server = http.createServer(app.callback());

// 创建socketIo实例
const io = SocketIo(server);

io.on('connection', function(socket) {
    socket.emit('to-client', 'hi welcome');
    socket.on('to-server', function(data) {
        console.log(data);
        socket.emit('to-client', 'haha im server');
    });
});

io.use((socket, next) => {

    socket.emit('to-client', { hello: 'world' });

    // console.log('a client');
    // const name = socket.handshake.query.name;
    // if (!name) {
    //     next(new Error('empty'));
    // }
    next();
})

// 注册静态服务器，一定要放在socketIo实例化后面
app.use(serve(path.join(__dirname)));
console.log(path.join(__dirname))

// 监听
server.listen(port, hostname, () => {
    console.log(`server run at http://${hostname}:${port}`);
})